package com.uwlaser.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.uwlaser.base.PageInfo;
import com.uwlaser.base.QueryHelpMybatisPlus;
import com.uwlaser.base.impl.CommonServiceImpl;
import com.uwlaser.domain.FactoryModel;
import com.uwlaser.domain.FactoryPlanHaltProduction;
import com.uwlaser.domain.FactoryShift;
import com.uwlaser.service.FactoryPlanHaltProductionService;
import com.uwlaser.service.FactoryShiftHistoryService;
import com.uwlaser.service.dto.FactoryPlanHaltProductionDto;
import com.uwlaser.service.dto.FactoryPlanHaltProductionQueryParam;
import com.uwlaser.service.mapper.FactoryModelMapper;
import com.uwlaser.service.mapper.FactoryPlanHaltProductionMapper;
import com.uwlaser.utils.ConvertUtil;
import com.uwlaser.utils.PageUtil;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author huangpan
 * @date 2022-12-02
 */
@Service
@AllArgsConstructor
// @CacheConfig(cacheNames = FactoryPlanHaltProductionService.CACHE_KEY)
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class FactoryPlanHaltProductionServiceImpl extends CommonServiceImpl<FactoryPlanHaltProductionMapper, FactoryPlanHaltProduction> implements FactoryPlanHaltProductionService {

    // private final RedisUtils redisUtils;
    private final FactoryPlanHaltProductionMapper factoryPlanHaltProductionMapper;
    private final FactoryModelMapper factoryModelMapper;
    private final FactoryShiftHistoryService factoryShiftHistoryService;

    @Override
    public PageInfo<FactoryPlanHaltProductionDto> queryAll(FactoryPlanHaltProductionQueryParam query, Pageable pageable) {
        IPage<FactoryPlanHaltProduction> queryPage = PageUtil.toMybatisPage(pageable);
        IPage<FactoryPlanHaltProduction> page = factoryPlanHaltProductionMapper.selectPage(queryPage, QueryHelpMybatisPlus.getPredicate(query));
        return ConvertUtil.convertPage(page, FactoryPlanHaltProductionDto.class);
    }

    @Override
    public List<FactoryPlanHaltProductionDto> queryAll(FactoryPlanHaltProductionQueryParam query) {
        return ConvertUtil.convertList(factoryPlanHaltProductionMapper.selectList(QueryHelpMybatisPlus.getPredicate(query)), FactoryPlanHaltProductionDto.class);
    }

    @Override
    public FactoryPlanHaltProduction getById(Integer id) {
        return factoryPlanHaltProductionMapper.selectById(id);
    }

    @Override
    // @Cacheable(key = "'id:' + #p0")
    public FactoryPlanHaltProductionDto findById(Integer id) {
        return ConvertUtil.convert(getById(id), FactoryPlanHaltProductionDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(FactoryPlanHaltProductionDto resources) {
        FactoryPlanHaltProduction entity = ConvertUtil.convert(resources, FactoryPlanHaltProduction.class);
        return factoryPlanHaltProductionMapper.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateById(FactoryPlanHaltProductionDto resources) {
        FactoryPlanHaltProduction entity = ConvertUtil.convert(resources, FactoryPlanHaltProduction.class);
        //新增班次历史数据
        factoryShiftHistoryService.add(resources.getTemplateCode());
        int ret = factoryPlanHaltProductionMapper.updateById(entity);
        // delCaches(resources.id);
        return ret;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeByIds(Set<Integer> ids) {
        // delCaches(ids);
        //获取模板信息在
        List<FactoryPlanHaltProduction> factoryPlanHaltProductions = factoryPlanHaltProductionMapper.selectList(new LambdaQueryWrapper<FactoryPlanHaltProduction>()
                .in(FactoryPlanHaltProduction::getId, ids));
        //新增班次历史数据
        factoryShiftHistoryService.add(factoryPlanHaltProductions.get(0).getTemplateCode());
        return factoryPlanHaltProductionMapper.deleteBatchIds(ids);
    }

    @Override
    public List<FactoryPlanHaltProductionDto> getPlannedStop(FactoryPlanHaltProductionDto factoryPlanHaltProductionDto) {
        //获取工厂结构
        List<FactoryModel> factoryModelList = factoryModelMapper.selectList(new LambdaQueryWrapper<FactoryModel>().in(FactoryModel::getModelType, "0", "1", "2"));
        //根据模组类型获取计划停产信息
        List<FactoryPlanHaltProduction> data = getData(factoryModelList, factoryPlanHaltProductionDto.getTemplateCode(), "3");
        return ConvertUtil.convertList(data, FactoryPlanHaltProductionDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeById(Integer id) {
        Set<Integer> set = new HashSet<>(1);
        set.add(id);
        return this.removeByIds(set);
    }

    /**
     * 获取计划停机信息
     */
    public List<FactoryPlanHaltProduction> getData(List<FactoryModel> factoryModelList, String templateCode, String ModelType) {
        //获取计划停机
        List<FactoryPlanHaltProduction> factoryPlanHaltProductions = factoryPlanHaltProductionMapper.selectList(new LambdaQueryWrapper<FactoryPlanHaltProduction>()
                .eq(FactoryPlanHaltProduction::getTemplateCode, templateCode));
        if (CollectionUtils.isEmpty(factoryPlanHaltProductions)) {
            if (ModelType.equals("0")) {
                return null;
            }
            //获取当前类型详情信息
            List<FactoryModel> collect = factoryModelList.stream()
                    .filter(f -> f.getModelCode().equals(templateCode)).collect(Collectors.toList());
            Integer pid = collect.get(0).getPid();
            List<FactoryModel> collect1 = factoryModelList.stream().filter(f -> f.getId().equals(pid)).collect(Collectors.toList());
            String shiftCode = collect1.get(0).getModelCode();

            return getData(factoryModelList, shiftCode, collect1.get(0).getModelType());
        }
        return factoryPlanHaltProductions;
    }

    /*
    private void delCaches(Integer id) {
        redisUtils.delByKey(CACHE_KEY + "::id:", id);
    }

    private void delCaches(Set<Integer> ids) {
        for (Integer id: ids) {
            delCaches(id);
        }
    }*/

    /*
    @Override
    public void download(List<FactoryPlanHaltProductionDto> all, HttpServletResponse response) throws IOException {
      List<Map<String, Object>> list = new ArrayList<>();
      for (FactoryPlanHaltProductionDto factoryPlanHaltProduction : all) {
        Map<String,Object> map = new LinkedHashMap<>();
              map.put("所属模型", factoryPlanHaltProduction.getTemplateCode());
              map.put("名称", factoryPlanHaltProduction.getHolidaysName());
              map.put("时间类型;0：指定时间段，1：按周，2：按月", factoryPlanHaltProduction.getConfigType());
              map.put("开始时间", factoryPlanHaltProduction.getStartTime());
              map.put("结束时间", factoryPlanHaltProduction.getEndTime());
              map.put("备注说明", factoryPlanHaltProduction.getRemark());
              map.put("创建人", factoryPlanHaltProduction.getCreateBy());
              map.put("创建时间", factoryPlanHaltProduction.getCreateTime());
              map.put("更新人", factoryPlanHaltProduction.getUpdateBy());
              map.put("更新时间", factoryPlanHaltProduction.getUpdateTime());
        list.add(map);
      }
      FileUtil.downloadExcel(list, response);
    }*/
}
